import json
import os

from backend.model.scoring_model import score_essay_with_chatgpt

# """
# 优化前
# """
# # 【接口5.2.1】POST /visualization/radar  获取作文雷达图数据
# def get_radar_chart_data(user_id, essay_id, version_id):
#     """
#     生成雷达图数据（从存储文件中获取评分）
#     :param user_id: 用户ID
#     :param essay_id: 作文ID
#     :param version_id: 版本ID
#     :return: 包含评分维度的雷达图数据
#     """
#     try:
#         # 评分存储路径
#         STORAGE_DIR = "../data/raw/analysis_data"
#         file_path = os.path.join(STORAGE_DIR, f"{user_id}_analysis.json")
#
#         if not os.path.exists(file_path):
#             return {"essay_id": essay_id, "message": "用户评分数据文件不存在", "dimensions": [], "values": []}
#
#         with open(file_path, "r", encoding="utf-8") as f:
#             try:
#                 user_scores = json.load(f)
#             except json.JSONDecodeError:
#                 return {"essay_id": essay_id, "message": "评分数据解析错误", "dimensions": [], "values": []}
#
#         # 确保 essay_id 存在于评分数据中
#         if essay_id not in user_scores:
#             return {"essay_id": essay_id, "message": "作文 ID 未找到", "dimensions": [], "values": []}
#
#         # 查找对应的版本评分
#         version_data = next((v for v in user_scores[essay_id]["analysis"] if v["version_id"] == str(version_id)), None)
#
#         if not version_data:
#             return {"essay_id": essay_id, "message": "版本 ID 未找到", "dimensions": [], "values": []}
#
#         # 提取四个维度的总分
#         labels = ["词汇得分", "句子得分", "结构得分", "内容得分"]
#         values = [
#             version_data.get("vocabulary_score", {}).get("total", 0),
#             version_data.get("sentence_score", {}).get("total", 0),
#             version_data.get("structure_score", {}).get("total", 0),
#             version_data.get("content_score", {}).get("total", 0)
#         ]
#
#         return {"essay_id": essay_id,
#                 "version_id": version_id,
#                 "dimensions": labels,
#                 "values": values}
#
#     except Exception as e:
#         print(f"【接口5.2.1】雷达图数据生成失败: {e}")
#         return {"essay_id": essay_id, "message": "服务器内部错误", "dimensions": [], "values": []}
"""
优化后
"""
# 【接口5.2.1】POST /visualization/radar  获取作文雷达图数据
def get_radar_chart_data(user_id, essay_id, version_id):
    """
    生成雷达图数据（从存储文件中获取评分）
    :param user_id: 用户ID
    :param essay_id: 作文ID
    :param version_id: 版本ID
    :return: 包含评分维度的雷达图数据
    """
    try:
        # 评分数据和映射文件路径
        STORAGE_DIR = "../data/raw/analysis_data"
        MAPPING_FILE = "../data/raw/score_dimension_mapping.json"
        file_path = os.path.join(STORAGE_DIR, f"{user_id}_analysis.json")

        if not os.path.exists(file_path):
            return {"essay_id": essay_id, "message": "用户评分数据文件不存在", "dimensions": [], "values": []}
        with open(file_path, "r", encoding="utf-8") as f:
            try:
                user_scores = json.load(f)
            except json.JSONDecodeError:
                return {"essay_id": essay_id, "message": "评分数据解析错误", "dimensions": [], "values": []}
        if essay_id not in user_scores:
            return {"essay_id": essay_id, "message": "作文 ID 未找到", "dimensions": [], "values": []}
        # 找到指定版本的评分记录
        version_data = next((v for v in user_scores[essay_id]["analysis"] if v["version_id"] == str(version_id)), None)
        if not version_data:
            return {"essay_id": essay_id, "message": "版本 ID 未找到", "dimensions": [], "values": []}

        # 加载映射文件
        if not os.path.exists(MAPPING_FILE):
            return {"essay_id": essay_id, "message": "维度映射文件不存在", "dimensions": [], "values": []}
        with open(MAPPING_FILE, "r", encoding="utf-8") as f:
            try:
                mapping_dict = json.load(f)
            except json.JSONDecodeError:
                return {"essay_id": essay_id, "message": "维度映射解析错误", "dimensions": [], "values": []}

        # 提取所有符合要求的维度
        dimensions = []
        values = []
        for key, val in version_data.items():
            if key.endswith("_score") and isinstance(val, dict) and "total" in val:
                zh_label = mapping_dict.get(key, key)  # 映射不到就用英文名
                dimensions.append(zh_label)
                values.append(val["total"])
        return {
            "essay_id": essay_id,
            "version_id": version_id,
            "dimensions": dimensions,
            "values": values
        }

    except Exception as e:
        print(f"【接口5.2.1】雷达图数据生成失败: {e}")
        return {"essay_id": essay_id, "message": "服务器内部错误", "dimensions": [], "values": []}


# 【接口5.2.2】POST /visualization/bar  获取作文得分柱状图数据
def get_bar_chart_data(user_id, essay_id):
    """
    生成作文得分柱状图数据
    :param user_id: 用户ID
    :param essay_id: 作文ID
    :return: 作文版本ID和对应评分的柱状图数据
    """
    try:
        # 定义文件路径
        analysis_file_path = f'../data/raw/analysis_data/{user_id}_analysis.json'
        if not os.path.exists(analysis_file_path):
            return {"essay_id": essay_id, "message": "用户分析数据文件不存在", "versions": [], "scores": []}
        with open(analysis_file_path, 'r', encoding='utf-8') as f:
            analysis_data = json.load(f)

        # 查找对应的 essay_id 数据
        essay_data = analysis_data.get(str(essay_id))
        if not essay_data:
            return {"essay_id": essay_id, "message": "作文 ID 未找到", "versions": [], "scores": []}

        # 获取每个版本的 overall_score
        version_ids = []
        overall_scores = []
        for analysis in essay_data["analysis"]:
            version_ids.append(analysis["version_id"])  # 获取版本ID
            overall_scores.append(analysis.get("overall_score", 0))  # 获取整体得分，默认值为0

        return {"essay_id": essay_id, "version_ids": version_ids, "scores": overall_scores}

    except Exception as e:
        print(f"【接口5.2.2】作文得分柱状图数据生成失败: {e}")
        return None


# 【接口5.2.3】POST /visualization/trend  获取评分趋势数据
def get_score_trend_data(user_id, essay_id):
    """
    从本地JSON文件获取评分趋势数据，模仿接口5.2.2的读取逻辑
    :param user_id: 用户ID
    :param essay_id: 作文ID
    :return: 时间序列上的评分变化趋势
    """
    try:
        file_path = f'../data/raw/analysis_data/{user_id}_analysis.json'
        if not os.path.exists(file_path):
            return {"user_id": user_id, "essay_id": essay_id, "versions": []}
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)

            # 查找对应的 essay_id 数据
            essay_data = data.get(str(essay_id))
            if not essay_data:
                return {"user_id": user_id, "essay_id": essay_id, "versions": []}

            # 获取每个版本的版本号、评分、时间戳
            versions = []
            for analysis in essay_data.get("analysis", []):
                versions.append({
                    "version_id": analysis.get("version_id"),
                    "overall_score": analysis.get("overall_score", 0),
                    "timestamp": analysis.get("timestamp", "未知时间")
                })

            return {"user_id": user_id, "essay_id": essay_id, "versions": versions}
    except Exception as e:
        print(f"【接口5.2.3】评分趋势数据生成失败: {e}")
        return {"user_id": user_id, "essay_id": essay_id, "versions": []}



# 【接口5.2.4】POST /visualization/comparison  获取评分维度对比数据
def get_comparison_chart_data(essay_id_1, essay_text_1, essay_id_2, essay_text_2):
    """
    生成评分维度对比数据
    :param essay_id_1: 第一篇作文ID
    :param essay_text_1: 第一篇作文文本
    :param essay_id_2: 第二篇作文ID
    :param essay_text_2: 第二篇作文文本
    :return: 两篇作文在各评分维度上的对比数据
    """
    try:
        result_1 = score_essay_with_chatgpt(essay_text_1)
        result_2 = score_essay_with_chatgpt(essay_text_2)

        labels = ["语法准确性", "内容连贯性", "词汇多样性", "平均单词长度"]

        scores_1 = [
            result_1["details"]["grammar_score"],
            result_1["details"]["coherence_score"],
            result_1["details"]["lexical_diversity"] * 10,
            result_1["details"]["avg_word_length"]
        ]

        scores_2 = [
            result_2["details"]["grammar_score"],
            result_2["details"]["coherence_score"],
            result_2["details"]["lexical_diversity"] * 10,
            result_2["details"]["avg_word_length"]
        ]

        return {"essay_1": {"essay_id": essay_id_1, "scores": scores_1},
                "essay_2": {"essay_id": essay_id_2, "scores": scores_2},
                "dimensions": labels}
    except Exception as e:
        print(f"【接口5.2.4】评分维度对比数据生成失败: {e}")
        return None

